<template>
  <div class="ele-body">
    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="farmId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">

            <!-- 牧场字段可编辑 -->
            <template v-if="column.dataIndex === 'ranchName'">
              <div v-if="editingId === record.farmId && editingField === 'ranchName'">
                <div style="display: flex; flex-direction: column; position: relative;">
                  <a-select
                    v-model:value="editingRanchId"
                    style="width: 180px; margin-bottom: 4px;"
                    placeholder="请选择牧场"
                    :dropdown-style="{ maxWidth: '300px' }"
                    :dropdown-match-select-width="false"
                    placement="bottomLeft"
                  >
                    <a-select-option v-for="item in tempRanchList" :key="item.ranchId">
                      {{ item.ranchName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveRanch(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.ranchName }}</span>
                  <a-button type="link" size="small" @click="startEditRanch(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>
</template>

<script>
import { DeviceAiEdgeFarmApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeFarmApi';
import { RanchApi } from '@/api/property/RanchApi';
import { message } from 'ant-design-vue';
export default {
  name: 'DeviceManagerdeviceAiedgeComputerHazzxFarmList',
  components: {
  },
  async mounted() {
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
            title: '牧云汇牧场ID',
            dataIndex: 'farmId'
        },
        {
          title: '牧云汇牧场名称',
          dataIndex: 'name'
        },
        {
          title: '关联的牛能汇牧场名称',
          dataIndex: 'ranchName'
        },
        {
          title: '地址',
          dataIndex: 'location'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
        }
      ],
      // 表格搜索条件
      where: {},
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      editingId: null,
      editingValue: null,
      // 添加新的编辑状态变量
      editingField: null,
      editingRanchId: null,
      // 临时存储编辑时的选项列表
      tempRanchList: [],
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    reset() {
      this.where = {};
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    async remove(row) {
      const result = await DeviceAiEdgeFarmApi.delete({ farmId: row.farmId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceAiEdgeFarmApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },

    /**
     * 开始编辑牧场
     */
    async startEditRanch(record) {
      this.editingId = record.farmId;
      this.editingField = 'ranchName';
      this.editingRanchId = record.ranchId == 0 ? undefined : record.ranchId;
      if (this.tempRanchList.length == 0) {
        // 获取牧场列表
        try {
          const resp = await RanchApi.list({});
          this.tempRanchList = (resp ? resp.data : null) || [];
        } catch (err) {
          console.log(err);
          message.error('获取牧场列表失败' + (err.message || '未知错误'));
        }
      }
    },
    /**
     * 保存牧场
     */
    async saveRanch(record) {
      try {
        const updateData = {
          farmId: record.farmId,
          ranchId: this.editingRanchId
        };
        
        await DeviceAiEdgeFarmApi.edit(updateData);
        message.success('牧场更新成功');
        
        // 更新当前记录的牧场信息
        const selectedRanch = this.tempRanchList.find(item => item.ranchId === this.editingRanchId);
        if (selectedRanch) {
          record.ranchId = selectedRanch.ranchId;
          record.ranchName = selectedRanch.ranchName;
        }
        this.cancelEdit();
      } catch (error) {
        message.error('牧场更新失败' + (error.message || '未知错误'));
      }
    },
    /**
     * 取消编辑
     */
    cancelEdit() {
      this.editingId = null;
      this.editingValue = null;
      this.editingField = null;
      this.editingRanchId = null;
    },

  }
};
</script>